package com.ccsc.auth.service.impl;

import com.ccsc.auth.dao.PositionDao;
import com.ccsc.auth.dao.SysUserDao;
import com.ccsc.auth.dao.UserDao;
import com.ccsc.auth.entity.*;
import com.ccsc.auth.service.*;
import com.ccsc.auth.utils.DataMap;
import com.ccsc.auth.utils.MD5;
import com.ccsc.auth.utils.Page;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.base.Strings;
import com.mysql.fabric.xmlrpc.base.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户serviceimpl
 * Created by XingWen on 2016/3/29.
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PositionDao positionDao;

    @Override
    public SysUser verifyAccount(DataMap params) throws Exception {
        SysUser user=new SysUser();
        user.setAccount((String) params.get("account"));
        user.setPassword((String) params.get("password"));
        SysUser loginUser = sysUserDao.verifyAccount(user);
        return loginUser;
    }

    /**
     *添加用户 包括 部门职位 授权信息
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public Integer createUser(SysUser user) throws Exception {
        //添加个人信息
        if(!Strings.isNullOrEmpty(user.getPassword())){
            user.setPassword(MD5.MD5Encode(user.getPassword()));
        }
        int i=sysUserDao.createUser(user);
//需要调试
        if (i > 0){
            //在用户管理系统中添加一个用户
            User u = SysUser2User(user);
            i = userDao.createUser(u);
            //添加部门
            for (Map<Department,Position> departmentPositionMap:u.getPositionMap()){
                Map<Department,Position> map = new HashMap<>();
                Iterator iter = departmentPositionMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    Department key = (Department) entry.getKey();
                    Position val = (Position) entry.getValue();
                    val.setDepartment(key);
                    positionDao.createDepartmentAndPosition(val);
                    userDao.createUserAndPosition(u.getId(), val.getRdop_id());

                }
            }
            userDao.createUserAndRole(u);
        }

        return i;
    }

    private User SysUser2User(SysUser sysUser) throws Exception{
        User user = new User();
        user.setAccount(sysUser.getAccount());
        user.setName(sysUser.getName());
        user.setPassword(sysUser.getPassword());
        user.setSex(1);
        user.setMail(sysUser.getEmail());
        user.setPhone(sysUser.getTel());
        user.setStatus(1);
        user.setSysuserid(sysUser.getId());
        //添加默认角色与职位
        Department department=new Department();
        department.setId(1);
        Position position=new Position();
        position.setId(2);
        position.setDepartment(department);
        position.setRdop_id(0);
        Map<Department,Position> departmentPositionMap=new ManagedMap<>();
        departmentPositionMap.put(department,position);
        List<Map<Department,Position>> mapList=new ArrayList<>();
        mapList.add(departmentPositionMap);
        user.setPositionMap(mapList);
        List<Role> roleList=new ArrayList<>();
        Role role = new Role();
        role.setId(9);
        roleList.add(role);
        user.setRoleList(roleList);
        user.setVerify_type(0);

        return user;
    }

    @Override
    public List<SysUser> getAllUsers() throws Exception {
        List<SysUser> userList=sysUserDao.getAllUsers();

        return userList;

    }

    @Override
    public List<SysUser> getUsersByAccount(String account) throws Exception {
        SysUser user=new SysUser();
        user.setAccount(account);
        return sysUserDao.getUsersByCondition(user);
    }

    @Override
    public Page getUsersByPage(DataMap params) throws Exception {
        //datamap 中roleId 表示角色id，status表示角色状态，keyWord表示关键字
        List<SysUser> resultList=null;
        try {
            resultList = sysUserDao.getAllUsers(params,new PageBounds(params.getInt("page"), params.getInt("pageSize")));

        }catch (Exception e){
            e.printStackTrace();
        }

        PageList<SysUser> pageList = (PageList<SysUser>) resultList;
        return new Page(pageList);
    }

    @Override
    public Page getUsersByPage(SysUser user, DataMap params) throws Exception {
        return null;
    }

    @Override
    public SysUser getUserById(Integer id) throws Exception {
        SysUser userParam =new SysUser();
        userParam.setId(id);
        SysUser user=sysUserDao.getUserInfoById(userParam);
        if(user==null){return null;}

        return user;
    }

    @Override
    public SysUser getUserByAccount(String account) throws Exception {
        SysUser user=new SysUser();
        user.setAccount(account);
        return sysUserDao.verifyAccount(user);
    }

    @Override
    public Integer updateUser(SysUser sysUser) throws Exception {

        if(!Strings.isNullOrEmpty(sysUser.getPassword())){
            sysUser.setPassword(MD5.MD5Encode(sysUser.getPassword()));
        }

        int result = sysUserDao.updateUser(sysUser);

        if (result > 0){
            //在用户管理系统中修改一个用户
            DataMap params = new DataMap();
            params.put("sysId",sysUser.getId());
            int userId = userDao.getUserIdBySysId(params);
            if (userId > 0){
                User user = new User();
                user.setId(userId);
                user.setAccount(sysUser.getAccount());
                user.setName(sysUser.getName());
                user.setPassword(sysUser.getPassword());
                user.setMail(sysUser.getEmail());
                user.setPhone(sysUser.getTel());
                user.setStatus(sysUser.getStatus());
                result = userDao.updateUser(user);
            }
        }

        return result;
    }

    @Override
    public Integer deleteUserById(Integer id) throws Exception {
        SysUser sysUser=new SysUser();
        sysUser.setId(id);
        DataMap params = new DataMap();
        params.put("user", sysUser);
        //删除用户的个人信息
        int i=sysUserDao.deleteUser(sysUser);

        if (i > 0){
            params.put("sysId",id);
            int userId = userDao.getUserIdBySysId(params);
            if (userId > 0){
                User user=new User();
                user.setId(userId);
                //删除用户的所有部门职位
                int j = userDao.deleteUserAndPosition(user.getId(),null,null);
                params = new DataMap();
                params.put("user", user);
                params.put("roleId", null);
                //删除用户的所有角色信息
                int k=userDao.deleteUserAndRole(params);
                //删除用户的个人信息
                i=userDao.deleteUser(user);
            }
        }

        return i;
    }

}
